MdEditor<template>
    <div class='container'>
        <div class="menu">
            <t-button class="back" @click="safeGoBack">返回</t-button>
            <div class="title"><t-input placeholder="请输入标题"></t-input></div>
            <div class="tag">
                <t-tag closable v-for="(tag, index) in tags" :key="index" @close="closeTag(index)">
                    {{ tag }}
                </t-tag closable>
                <div class="title">
                    <t-input placeholder="请输入标签" @enter="addTag" v-model="tag">
                    </t-input>
                </div>
            </div>
        </div>
        <div class="edit">
            <MdEditor v-model="text" @on-save="handleSave" class="edit-md" />
        </div>
    </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router'
import { ref, onMounted } from 'vue';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';

const router = useRouter()
const content = ref()
const text = ref(`# This is a god student
> Hello \n\`\`\`
import pandas as pd\n\`\`\`\n
$$
\\frac{a^2}{2x^2+bx+c}
$$
`);

const tags = ref(['12', '212', '212'])
const tag = ref('')
const closeTag = (index: number) => {
    // console.log(index)
    tags.value = tags.value.filter((_, i) => i != index)
}

const addTag = () => {
    if (tag.value) {
        tags.value.push(tag.value)
        tag.value = ''

    }
}
const handleSave = (text: string) => {
    // console.log(text);
    content.value = escapeString(text)
    console.log(content.value)
}

const safeGoBack = () => {
    // 如果有上一页，就返回；否则跳转到默认页面（如列表页）
    if (window.history.length > 1) {
        router.go(-1)
    } else {
        router.push('/blog') // 假设列表页路径是 /blog
    }
}
function escapeString(str: string): string {
    return str
        .replace(/[\\"]/g, '\\$&')  // 转义 \ 和 "
        .replace(/\n/g, '\\n')
        .replace(/\t/g, '\\t')
        .replace(/\r/g, '\\r')
        .replace(/\f/g, '\\f')
        .replace(/\`/g, '\\`')
}
</script>
<style lang='scss' scoped>
.container {
    height: 100vh;

    .menu {
        display: inline-flex;
        width: 100%;
        height: 40px;
        gap: 10px;
        align-items: center;

        .title {
            width: 50%;
        }
    }

    .tag {
        gap: 10px;
        align-items: center;
        display: inline-flex;
        height: 40px;
    }

    .edit-md {
        height: calc(100vh - 80px);
    }
}
</style>